import { Tab } from '../../../contexts/AppContext';
import { TabManager } from './TabManager';
import { CookieManager } from './CookieManager';

export interface PersistentSession {
  version: string;
  savedAt: string;
  tabs: PersistentTab[];
  activeTabId: string | null;
}

export interface PersistentTab {
  id: string;
  url: string;
  title: string;
  accountId?: string;
  platform?: string;
  createdAt: string;
  lastActive: string;
  cookies: Array<[string, any]>; // [name, CookieData]
  localStorage: Array<[string, any]>;
  favicon?: string;
}

export class SessionPersistence {
  private static readonly STORAGE_KEY = 'browser_sessions_v2';
  private static readonly VERSION = '2.0.0';
  private tabManager: TabManager;

  constructor(tabManager: TabManager) {
    this.tabManager = tabManager;
  }

  // 保存当前会话状态
  saveSession(tabs: Tab[], activeTabId: string | null): void {
    try {
      const persistentTabs: PersistentTab[] = tabs.map(tab => {
        const session = this.tabManager.getSession(tab.id);
        
        return {
          id: tab.id,
          url: tab.url,
          title: tab.title,
          accountId: tab.accountId,
          platform: tab.platform,
          createdAt: tab['createdAt'] || new Date().toISOString(),
          lastActive: new Date().toISOString(),
          cookies: session ? Array.from(session.cookies.entries()) : [],
          localStorage: session ? Array.from(session.localStorage.entries()) : [],
          favicon: tab.favicon
        };
      });

      const session: PersistentSession = {
        version: SessionPersistence.VERSION,
        savedAt: new Date().toISOString(),
        tabs: persistentTabs,
        activeTabId
      };

      localStorage.setItem(SessionPersistence.STORAGE_KEY, JSON.stringify(session));
      console.log('会话状态已保存', { tabCount: tabs.length, activeTabId });
    } catch (error) {
      console.error('保存会话状态失败:', error);
    }
  }

  // 加载保存的会话状态
  loadSession(): { tabs: Tab[], activeTabId: string | null } | null {
    try {
      const stored = localStorage.getItem(SessionPersistence.STORAGE_KEY);
      if (!stored) {
        return null;
      }

      const session: PersistentSession = JSON.parse(stored);
      
      // 检查版本兼容性
      if (session.version !== SessionPersistence.VERSION) {
        console.warn('会话版本不兼容，跳过恢复');
        return null;
      }

      // 转换回Tab对象
      const tabs: Tab[] = session.tabs.map(persistentTab => {
        const tab: Tab = {
          id: persistentTab.id,
          url: persistentTab.url,
          title: persistentTab.title,
          accountId: persistentTab.accountId,
          platform: persistentTab.platform,
          isActive: false, // 将在外部设置活跃状态
          favicon: persistentTab.favicon
        };

        // 恢复会话数据
        this.restoreTabSession(persistentTab);

        return tab;
      });

      console.log('会话状态已恢复', { tabCount: tabs.length, activeTabId: session.activeTabId });
      return { tabs, activeTabId: session.activeTabId };
    } catch (error) {
      console.error('加载会话状态失败:', error);
      return null;
    }
  }

  // 恢复单个标签页的会话数据
  private restoreTabSession(persistentTab: PersistentTab): void {
    try {
      // 创建或获取会话
      let session = this.tabManager.getSession(persistentTab.id);
      if (!session) {
        session = this.tabManager.createSession(persistentTab.id, {
          accountId: persistentTab.accountId,
          platform: persistentTab.platform,
          initialUrl: persistentTab.url
        });
      }

      // 恢复Cookie
      persistentTab.cookies.forEach(([name, cookieData]) => {
        session.cookies.setCookie(cookieData);
      });

      // 恢复localStorage
      persistentTab.localStorage.forEach(([key, value]) => {
        session.localStorage.set(key, value);
      });

      console.log(`标签页会话已恢复: ${persistentTab.id}`, {
        cookies: persistentTab.cookies.length,
        localStorage: persistentTab.localStorage.length
      });
    } catch (error) {
      console.error(`恢复标签页会话失败: ${persistentTab.id}`, error);
    }
  }

  // 清除所有保存的会话
  clearSession(): void {
    try {
      localStorage.removeItem(SessionPersistence.STORAGE_KEY);
      console.log('会话状态已清除');
    } catch (error) {
      console.error('清除会话状态失败:', error);
    }
  }

  // 导出会话数据（用于备份）
  exportSession(): string {
    try {
      const stored = localStorage.getItem(SessionPersistence.STORAGE_KEY);
      return stored || '';
    } catch (error) {
      console.error('导出会话数据失败:', error);
      return '';
    }
  }

  // 导入会话数据（从备份恢复）
  importSession(sessionData: string): boolean {
    try {
      const session: PersistentSession = JSON.parse(sessionData);
      
      // 验证数据格式
      if (!session.version || !session.tabs || !Array.isArray(session.tabs)) {
        throw new Error('无效的会话数据格式');
      }

      localStorage.setItem(SessionPersistence.STORAGE_KEY, sessionData);
      console.log('会话数据已导入');
      return true;
    } catch (error) {
      console.error('导入会话数据失败:', error);
      return false;
    }
  }

  // 检查是否有保存的会话
  hasSavedSession(): boolean {
    return localStorage.getItem(SessionPersistence.STORAGE_KEY) !== null;
  }

  // 获取会话信息摘要
  getSessionInfo(): { tabCount: number; savedAt: string; version: string } | null {
    try {
      const stored = localStorage.getItem(SessionPersistence.STORAGE_KEY);
      if (!stored) return null;

      const session: PersistentSession = JSON.parse(stored);
      return {
        tabCount: session.tabs.length,
        savedAt: session.savedAt,
        version: session.version
      };
    } catch (error) {
      console.error('获取会话信息失败:', error);
      return null;
    }
  }

  // 自动保存会话（防抖处理）
  private autoSaveTimeout: NodeJS.Timeout | null = null;
  
  autoSaveSession(tabs: Tab[], activeTabId: string | null, delay: number = 1000): void {
    if (this.autoSaveTimeout) {
      clearTimeout(this.autoSaveTimeout);
    }

    this.autoSaveTimeout = setTimeout(() => {
      this.saveSession(tabs, activeTabId);
      this.autoSaveTimeout = null;
    }, delay);
  }

  // 手动触发立即保存
  forceSaveSession(tabs: Tab[], activeTabId: string | null): void {
    if (this.autoSaveTimeout) {
      clearTimeout(this.autoSaveTimeout);
      this.autoSaveTimeout = null;
    }
    this.saveSession(tabs, activeTabId);
  }
}

// 会话管理器 - 单例模式
export class SessionManager {
  private static instance: SessionManager;
  private persistence: SessionPersistence;
  private tabManager: TabManager;

  private constructor() {
    this.tabManager = new TabManager();
    this.persistence = new SessionPersistence(this.tabManager);
    
    // 监听页面卸载事件，确保会话被保存
    this.setupBeforeUnloadListener();
  }

  static getInstance(): SessionManager {
    if (!SessionManager.instance) {
      SessionManager.instance = new SessionManager();
    }
    return SessionManager.instance;
  }

  // 设置页面卸载监听器
  private setupBeforeUnloadListener(): void {
    if (typeof window !== 'undefined') {
      window.addEventListener('beforeunload', () => {
        // 这里可以添加紧急保存逻辑
        console.log('页面即将卸载，会话状态将被保存');
      });
    }
  }

  // 获取TabManager实例
  getTabManager(): TabManager {
    return this.tabManager;
  }

  // 获取SessionPersistence实例
  getPersistence(): SessionPersistence {
    return this.persistence;
  }

  // 检查是否有待恢复的会话
  shouldRestoreSession(): boolean {
    return this.persistence.hasSavedSession();
  }

  // 显示恢复会话的确认对话框
  async showRestoreDialog(): Promise<boolean> {
    const sessionInfo = this.persistence.getSessionInfo();
    if (!sessionInfo) return false;

    // 在实际应用中，这里可以显示一个确认对话框
    const savedTime = new Date(sessionInfo.savedAt).toLocaleString();
    const message = `检测到有 ${sessionInfo.tabCount} 个标签页的会话状态（保存于 ${savedTime}）。是否恢复？`;
    
    // 模拟用户确认（实际应用中应该显示真实的对话框）
    return window.confirm(message);
  }

  // 完整的会话恢复流程
  async restoreSessionIfNeeded(): Promise<{ tabs: Tab[], activeTabId: string | null } | null> {
    if (!this.shouldRestoreSession()) {
      return null;
    }

    const shouldRestore = await this.showRestoreDialog();
    if (!shouldRestore) {
      // 用户选择不恢复，清除保存的会话
      this.persistence.clearSession();
      return null;
    }

    return this.persistence.loadSession();
  }

  // 定期自动保存（用于长时间运行的会话）
  startAutoSave(tabsProvider: () => { tabs: Tab[], activeTabId: string | null }, interval: number = 30000): void {
    setInterval(() => {
      const { tabs, activeTabId } = tabsProvider();
      this.persistence.autoSaveSession(tabs, activeTabId, 500);
    }, interval);
  }
}